#ifndef __scheduler_h__
#define __scheduler_h__

#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <vector>

#include "interface.h"
#include "step.h"

class Workflow : public IWorkflowNotify, public IDataCollectionSupport {
 private:
  std::string name_;
  std::vector<std::shared_ptr<Step>> steps_;
  size_t current_step_idx_ = 0;
  bool is_completed_ = false;
  bool is_failed_ = false;

 public:
  explicit Workflow(const std::string &name) : name_(name) {}

  void addStep(std::shared_ptr<Step> step) {
    if (step) {
      steps_.push_back(step);
    }
  }

  bool execute();
  bool isCompleted() const { return is_completed_; }
  bool isFailed() const { return is_failed_; }
  const std::string &getName() const { return name_; }

  void onStepFailed(const std::string &step_name,
                    const std::string &reason) override {
    is_failed_ = true;
    std::cout << "[" << name_ << "] 步骤失败：" << step_name << "（原因："
              << reason << "）" << std::endl;
  }

  std::string getWorkflowName() const override { return name_; }

  void prepareForCollection() const override {
    std::cout << "[" << name_ << "] 执行采集准备：移动到目标位置" << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(1));

    if (std::rand() % 10 < 3) {
      throw std::runtime_error("路径被阻挡");
    }
  }
};

// 调度器
class Scheduler {
 private:
  std::vector<std::shared_ptr<Workflow>> workflows_;
  std::chrono::milliseconds interval_;

 public:
  explicit Scheduler(std::chrono::milliseconds interval)
      : interval_(interval) {}

  void addWorkflow(std::shared_ptr<Workflow> workflow) {
    if (workflow) {
      workflows_.push_back(workflow);
    }
  }

  void start();
};

#endif